import { PageContainer, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Form,
  Popconfirm,
  Radio,
  Select,
  Space,
  InputNumber,
} from "antd";
import { connect } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useRef, useState } from "react";
import { history } from "@@/exports";
import { getItem } from "@/utils/localstorage";
import { TOKEN } from "@/constants";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { PlusOutlined } from "@ant-design/icons";

const Page = (props) => {
  const { dispatch, submitLoading, venueArr } = props;
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const actionRef = useRef();
  const [editor, setEditor] = useState(null);
  const [displaySort, setDisplaySort] = useState("");
  const [titleType, setTitleType] = useState(0);
  const [topFlagValue, setTopFlagValue] = useState("1");
  // 编辑器内容
  const [html, setHtml] = useState("");

  useEffect(() => {
    // dispatch({
    //   type: `${namespace}/pageInit`,
    // });
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  type InsertFnType = (url: string, alt: string, href: string) => void;
  const toolbarConfig = { excludeKeys: ["group-video"] };
  const editorConfig = {
    placeholder: "请输入内容", // JS 语法
    MENU_CONF: {
      uploadImage: {
        fieldName: "file",
        server: "/spark-frontend/system/user/uploadPic",
        allowedFileTypes: ["image/*"],
        headers: {
          clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
          Authorization: getItem(TOKEN),
        },

        customInsert(res: any, insertFn: InsertFnType) {
          if (res?.code == 200) {
            let { data } = res;
            insertFn(data, "", "");
          }
        },
      },
    },
  };
  const editInfo = (params) => {
    setTitleType(1);
    form.setFieldsValue({ ...params });
    setDisplaySort(params.displaySort);
    setTopFlagValue(params.topFlag);
    setHtml(params.noticeContent);
    setOpen(true);
  };

  const deleteItem = (params) => {
    dispatch({
      type: `${namespace}/deleteItem`,
      params,
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };
  const toggleState = (params) => {
    dispatch({
      type: `${namespace}/toggleState`,
      params,
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };

  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "left",
    hideInSearch: true,
    width: 350,
    render: (_, record) => {
      const _status = parseInt(record.status, 10);
      return (
        <Space>
          <Button type="link" onClick={() => editInfo(record)}>
            编辑
          </Button>
          <Button
            type="link"
            onClick={() =>
              history.push(`/content/announcement/detail/${record.id}`)
            }
          >
            详情
          </Button>
          {_status === 0 || _status === 2 ? (
            <Button
              type="link"
              danger
              onClick={() =>
                toggleState({
                  ...record,
                  status: 1,
                })
              }
            >
              上架
            </Button>
          ) : (
            <Popconfirm
              title="下架后前台将不可见，是否确认下架?"
              onConfirm={() =>
                toggleState({
                  ...record,
                  status: 2,
                })
              }
            >
              <Button type="link" danger>
                下架
              </Button>
            </Popconfirm>
          )}
          <Button type="link" onClick={() => copy(record)}>
            复制
          </Button>
          {_status === 0 ? (
            <Popconfirm
              title="删除后不可恢复，是否确定删除?"
              onConfirm={() => deleteItem({ noticeId: record.id })}
            >
              <Button type="link" danger>
                删除
              </Button>
            </Popconfirm>
          ) : null}
        </Space>
      );
    },
  };
  const copy = async (params) => {
    let { venueId, noticeTitle, topFlag, displaySort, noticeContent } = params;
    dispatch({
      type: `${namespace}/submitItem`,
      params: {
        venueId,
        noticeTitle,
        topFlag,
        displaySort,
        noticeContent,
        status: "0",
      },
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };
  const submitForm = async (status) => {
    form.setFieldsValue({ noticeContent: html == "<p><br></p>" ? "" : html });
    const res = await form.validateFields();
    if (res) {
      if (res.id) {
        dispatch({
          type: `${namespace}/toggleState`,
          params: {
            ...res,
            displaySort: displaySort ? displaySort : 0,
            status,
          },
          callback: () => {
            form.resetFields();
            setOpen(false);
            actionRef.current?.reload();
          },
        });
      } else {
        dispatch({
          type: `${namespace}/submitItem`,
          params: {
            ...res,
            displaySort: displaySort,
            status,
          },
          callback: () => {
            form.resetFields();
            setOpen(false);
            actionRef.current?.reload();
          },
        });
      }
    }
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setTitleType(0);
              form.resetFields();
              setDisplaySort("0");
              setHtml("");
              setOpen(true);
            }}
          >
            新增公告
          </Button>,
        ]}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        scroll={{ x: 1000 }}
        pagination={{
          showSizeChanger: true,
        }}
        columns={calcColumns({ operate })}
      />

      <Modal
        open={open}
        title={titleType ? "编辑公告" : "新增公告"}
        forceRender
        width={800}
        onCancel={() => setOpen(!open)}
        footer={
          <Space>
            <Button onClick={() => setOpen(false)}>取消</Button>
            <Button
              onClick={() => {
                submitForm("0");
              }}
              loading={submitLoading}
            >
              保存草稿
            </Button>
            <Button
              onClick={() => {
                submitForm("1");
              }}
              loading={submitLoading}
              type="primary"
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 18 }}
          initialValues={{ topFlag: "1" }}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            label="公告标题"
            name="noticeTitle"
            rules={[{ required: true, message: "请输入公告,长度不超过30个字" }]}
          >
            <Input maxLength={30} placeholder="请输入" showCount />
          </Form.Item>

          {/* <Form.Item
            label="所属场馆"
            name="venueId"
            rules={[{ required: true, message: "请选择所属场馆!" }]}
          >
            <Select>
              {venueArr.map((v) => (
                <Select.Option value={v.id}>{v.venueName}</Select.Option>
              ))}
            </Select>
          </Form.Item> */}

          <Form.Item
            label="显示顺序"
            name="topFlag"
            rules={[{ required: true, message: "请选择顺序" }]}
          >
            <Radio.Group
              onChange={(e) => {
                setTopFlagValue(e.target.value);
                setDisplaySort("0");
              }}
            >
              <Radio value="0">置顶</Radio>
              <Space>
                <Radio value="1">自定义</Radio>
                {topFlagValue == "1" && (
                  <InputNumber
                    min="0"
                    max="10000"
                    defaultValue="0"
                    placeholder="请输入排序值，数值越大越靠前"
                    value={displaySort}
                    precision={0}
                    controls={false}
                    style={{ width: "300px" }}
                    onChange={(e) => {
                      setDisplaySort(e);
                    }}
                  />
                )}
              </Space>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="内容"
            name="noticeContent"
            rules={[{ required: true, message: "请输入内容" }]}
          >
            <div id="courseIntroduce">
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ borderBottom: "1px solid #ccc" }}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor) => {
                  setHtml(editor.getHtml());
                  form.setFieldsValue({ noticeContent: editor.getHtml() });
                }}
                mode="default"
                style={{ height: "200px", overflowY: "hidden" }}
              />
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
